<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'

const router = useRouter()

// 订单列表
const orders = ref([])

// 分页参数
const pagination = ref({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 筛选条件
const filters = ref({
  status: '',
  dateRange: []
})

// 订单状态选项
const statusOptions = [
  { label: '全部', value: '' },
  { label: '待付款', value: 'unpaid' },
  { label: '待发货', value: 'unshipped' },
  { label: '待收货', value: 'shipped' },
  { label: '已完成', value: 'completed' },
  { label: '已取消', value: 'cancelled' }
]

/**
 * 加载订单列表
 * @description 从服务器获取当前用户的订单列表数据
 * @api GET /order/list
 * @params {number} currentPage - 当前页码
 * @params {number} pageSize - 每页显示数量
 * @params {string} [status] - 订单状态筛选，可选值：unpaid, unshipped, shipped, completed, cancelled
 * @params {Array} [dateRange] - 日期范围筛选，格式：[startDate, endDate]
 * @response {Array} data.list - 订单列表
 * @response {string} data.list[].id - 订单ID
 * @response {string} data.list[].status - 订单状态
 * @response {number} data.list[].totalAmount - 订单总金额
 * @response {string} data.list[].createTime - 订单创建时间
 * @response {Array} data.list[].products - 订单商品列表
 * @response {number} data.total - 订单总数
 */
const loadOrders = () => {
  // 这里应该调用API获取订单列表
  // API调用后端
  // getOrderListAPI({
  //   currentPage: pagination.value.currentPage,
  //   pageSize: pagination.value.pageSize,
  //   status: filters.value.status,
  //   dateRange: filters.value.dateRange
  // }).then(res => {
  //   orders.value = res.data.list
  //   pagination.value.total = res.data.total
  // })
  
  // 模拟数据
  orders.value = Array(10).fill(null).map((_, index) => ({
    id: `ORDER20240101000${index + 1}`,
    status: statusOptions[Math.floor(Math.random() * 5) + 1].value,
    totalAmount: Math.floor(Math.random() * 2000) + 500,
    createTime: '2024-01-01 10:00:00',
    products: [
      {
        id: 1,
        name: 'Air Jordan 1',
        image: 'https://via.placeholder.com/100x100?text=AJ1',
        price: 1299,
        quantity: 1
      }
    ]
  }))
  pagination.value.total = 100
}

// 处理页码变化
const handlePageChange = (page) => {
  pagination.value.currentPage = page
  loadOrders()
}

// 处理筛选条件变化
const handleFilterChange = () => {
  pagination.value.currentPage = 1
  loadOrders()
}

// 返回个人中心
const goBack = () => {
  router.push('/profile')
}

onMounted(() => {
  loadOrders()
})
</script>

<template>
  <div class="order-list">
    <div class="container">
      <el-card>
        <template #header>
          <div class="page-header">
            <div class="header-left">
              <el-button @click="goBack" text>
                <el-icon><ArrowLeft /></el-icon>
                返回
              </el-button>
              <h2>我的订单</h2>
            </div>
            <div class="header-right">
              <el-select v-model="filters.status" placeholder="订单状态" @change="handleFilterChange">
                <el-option
                  v-for="option in statusOptions"
                  :key="option.value"
                  :label="option.label"
                  :value="option.value"
                />
              </el-select>
              <el-date-picker
                v-model="filters.dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                @change="handleFilterChange"
              />
            </div>
          </div>
        </template>

        <el-table :data="orders" style="width: 100%">
          <el-table-column label="订单号" prop="id" width="180" />
          <el-table-column label="商品信息">
            <template #default="{ row }">
              <div v-for="product in row.products" :key="product.id" class="product-info">
                <el-image :src="product.image" :alt="product.name" class="product-image" />
                <div class="product-detail">
                  <h4>{{ product.name }}</h4>
                  <p>¥{{ product.price }} × {{ product.quantity }}</p>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="订单金额" width="120">
            <template #default="{ row }">
              <span class="price">¥{{ row.totalAmount }}</span>
            </template>
          </el-table-column>
          <el-table-column label="订单状态" width="120">
            <template #default="{ row }">
              <el-tag :type="row.status === 'completed' ? 'success' : row.status === 'cancelled' ? 'danger' : 'primary'">
                {{ statusOptions.find(option => option.value === row.status)?.label }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="下单时间" prop="createTime" width="180" />
          <el-table-column label="操作" width="120">
            <template #default="{ row }">
              <el-button
                v-if="row.status === 'unpaid'"
                type="primary"
                size="small"
                @click="handlePay(row.id)"
              >
                立即付款
              </el-button>
              <el-button
                v-if="row.status === 'shipped'"
                type="success"
                size="small"
                @click="handleConfirm(row.id)"
              >
                确认收货
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination">
          <el-pagination
            v-model:current-page="pagination.currentPage"
            :page-size="pagination.pageSize"
            :total="pagination.total"
            layout="prev, pager, next"
            @current-change="handlePageChange"
          />
        </div>
      </el-card>
    </div>
  </div>
</template>

<style scoped>
.order-list {
  padding: 24px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.header-left h2 {
  margin: 0;
  font-size: 20px;
}

.header-right {
  display: flex;
  gap: 12px;
}

.product-info {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 8px;
}

.product-info:last-child {
  margin-bottom: 0;
}

.product-image {
  width: 60px;
  height: 60px;
  border-radius: 4px;
}

.product-detail h4 {
  margin: 0 0 4px;
  font-size: 14px;
}

.product-detail p {
  margin: 0;
  color: #909399;
  font-size: 12px;
}

.price {
  color: #f56c6c;
  font-weight: bold;
}

.pagination {
  margin-top: 24px;
  text-align: center;
}
</style>